<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>活动详情</span>
          <div>
            <el-button type="primary" icon="Edit" @click="handleEdit" v-hasPermi="['activity:edit']">编辑</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="活动名称">{{ activityInfo.activityName }}</el-descriptions-item>
        <el-descriptions-item label="活动类型">{{ activityInfo.typeName }}</el-descriptions-item>
        <el-descriptions-item label="活动开始时间">{{ formatDateTime(activityInfo.activityStartTime) }}</el-descriptions-item>
        <el-descriptions-item label="活动结束时间">{{ formatDateTime(activityInfo.activityEndTime) }}</el-descriptions-item>
        <el-descriptions-item label="活动地点">{{ activityInfo.location }}</el-descriptions-item>
        <el-descriptions-item label="参与人数">{{ activityInfo.currentParticipants || 0 }}/{{ activityInfo.maxParticipants }}</el-descriptions-item>
        <el-descriptions-item label="主持人">{{ activityInfo.hostMemberName }}</el-descriptions-item>
        <el-descriptions-item label="活动状态">
          <el-tag :type="getStatusType(activityInfo.status)">
            {{ getStatusLabel(activityInfo.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="活动描述" :span="2">
          {{ activityInfo.description }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 活动参与记录 -->
      <div class="mt20">
        <el-divider content-position="left">活动参与记录</el-divider>
        <el-table v-loading="participantLoading" :data="participantList">
          <el-table-column label="参与者ID" align="center" prop="memberId" />
          <el-table-column label="参与者姓名" align="center" prop="memberName" />
          <el-table-column label="是否出席" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isAttended ? 'success' : 'danger'">
                {{ scope.row.isAttended ? '已出席' : '未出席' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="出席时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.attendanceTime) }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="notes" :show-overflow-tooltip="true" />
        </el-table>
        <div class="mt10 text-right">
          <el-button type="primary" @click="handleAddParticipant" v-hasPermi="['activity:participant:add']">
            添加参与记录
          </el-button>
        </div>
      </div>

      <!-- 活动评价 -->
      <div class="mt20">
        <el-divider content-position="left">活动评价</el-divider>
        <el-table v-loading="ratingLoading" :data="ratingList">
          <el-table-column label="评价者ID" align="center" prop="reviewerId" />
          <el-table-column label="评价者姓名" align="center" prop="reviewerName" />
          <el-table-column label="评分" align="center">
            <template #default="scope">
              <el-rate v-model="scope.row.rating" disabled show-score />
            </template>
          </el-table-column>
          <el-table-column label="反馈内容" align="center" prop="feedback" :show-overflow-tooltip="true" />
        </el-table>
        <div class="mt10 text-right">
          <el-button type="primary" @click="handleAddRating" v-hasPermi="['activity:rating:add']">
            添加评价
          </el-button>
        </div>
      </div>

      <!-- 活动预算 -->
      <div class="mt20">
        <el-divider content-position="left">活动预算</el-divider>
        <el-table v-loading="budgetLoading" :data="budgetList">
          <el-table-column label="项目名称" align="center" prop="itemName" />
          <el-table-column label="预估金额" align="center" prop="estimatedAmount" />
          <el-table-column label="实际金额" align="center" prop="actualAmount" />
          <el-table-column label="支出日期" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.expenseDate) }}
            </template>
          </el-table-column>
          <el-table-column label="支付方式" align="center" prop="paymentMethod" />
          <el-table-column label="备注" align="center" prop="notes" :show-overflow-tooltip="true" />
        </el-table>
        <div class="mt10 text-right">
          <el-button type="primary" @click="handleAddBudget" v-hasPermi="['activity:budget:add']">
            添加预算
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 添加参与记录对话框 -->
    <el-dialog v-model="participantDialogVisible" title="添加参与记录" width="500px" append-to-body>
      <el-form ref="participantFormRef" :model="participantForm" :rules="participantRules" label-width="100px">
        <el-form-item label="参与者" prop="memberId">
          <el-select v-model="participantForm.memberId" placeholder="请选择参与者" style="width: 100%">
            <el-option
              v-for="item in memberOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否出席" prop="isAttended">
          <el-switch v-model="participantForm.isAttended" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="出席时间" prop="attendanceTime" v-if="participantForm.isAttended === 1">
          <el-date-picker
            v-model="participantForm.attendanceTime"
            type="datetime"
            placeholder="选择出席时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="participantForm.notes" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="participantDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitParticipant">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加评价对话框 -->
    <el-dialog v-model="ratingDialogVisible" title="添加评价" width="500px" append-to-body>
      <el-form ref="ratingFormRef" :model="ratingForm" :rules="ratingRules" label-width="100px">
        <el-form-item label="评价者" prop="reviewerId">
          <el-select v-model="ratingForm.reviewerId" placeholder="请选择评价者" style="width: 100%">
            <el-option
              v-for="item in memberOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="ratingForm.rating" :max="5" show-score />
        </el-form-item>
        <el-form-item label="反馈内容" prop="feedback">
          <el-input v-model="ratingForm.feedback" type="textarea" :rows="3" placeholder="请输入反馈内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ratingDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRating">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加预算对话框 -->
    <el-dialog v-model="budgetDialogVisible" title="添加预算" width="500px" append-to-body>
      <el-form ref="budgetFormRef" :model="budgetForm" :rules="budgetRules" label-width="100px">
        <el-form-item label="项目名称" prop="itemName">
          <el-input v-model="budgetForm.itemName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="预估金额" prop="estimatedAmount">
          <el-input-number v-model="budgetForm.estimatedAmount" :precision="2" :step="100" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="实际金额" prop="actualAmount">
          <el-input-number v-model="budgetForm.actualAmount" :precision="2" :step="100" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="支出日期" prop="expenseDate">
          <el-date-picker
            v-model="budgetForm.expenseDate"
            type="date"
            placeholder="选择支出日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="budgetForm.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
            <el-option label="现金" value="CASH" />
            <el-option label="银行转账" value="BANK_TRANSFER" />
            <el-option label="微信支付" value="WECHAT_PAY" />
            <el-option label="支付宝" value="ALIPAY" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="budgetForm.notes" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="budgetDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitBudget">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import ActivityAPI from '@/api/activity.api';

const route = useRoute();
const router = useRouter();
const activityId = ref(route.params.id);

// 活动信息
const activityInfo = ref({});
// 参与记录列表
const participantList = ref([]);
// 评价列表
const ratingList = ref([]);
// 预算列表
const budgetList = ref([]);

// 加载状态
const participantLoading = ref(false);
const ratingLoading = ref(false);
const budgetLoading = ref(false);

// 对话框显示状态
const participantDialogVisible = ref(false);
const ratingDialogVisible = ref(false);
const budgetDialogVisible = ref(false);

// 会员选项
const memberOptions = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' }
]);

// 活动状态选项
const activityStatusOptions = ref([
  { value: 'PLANNED', label: '计划中' },
  { value: 'ONGOING', label: '进行中' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'CANCELLED', label: '已取消' }
]);

// 参与记录表单
const participantFormRef = ref();
const participantForm = reactive({
  activityId: undefined,
  memberId: undefined,
  isAttended: 1,
  attendanceTime: new Date(),
  notes: ''
});

// 参与记录表单校验规则
const participantRules = reactive({
  memberId: [
    { required: true, message: '请选择参与者', trigger: 'change' }
  ],
  isAttended: [
    { required: true, message: '请选择是否出席', trigger: 'change' }
  ],
  attendanceTime: [
    { required: true, message: '请选择出席时间', trigger: 'change' }
  ]
});

// 评价表单
const ratingFormRef = ref();
const ratingForm = reactive({
  activityId: undefined,
  reviewerId: undefined,
  rating: 5,
  feedback: ''
});

// 评价表单校验规则
const ratingRules = reactive({
  reviewerId: [
    { required: true, message: '请选择评价者', trigger: 'change' }
  ],
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ]
});

// 预算表单
const budgetFormRef = ref();
const budgetForm = reactive({
  activityId: undefined,
  itemName: '',
  estimatedAmount: 0,
  actualAmount: 0,
  expenseDate: new Date(),
  paymentMethod: 'CASH',
  notes: ''
});

// 预算表单校验规则
const budgetRules = reactive({
  itemName: [
    { required: true, message: '请输入项目名称', trigger: 'blur' }
  ],
  estimatedAmount: [
    { required: true, message: '请输入预估金额', trigger: 'blur' }
  ],
  expenseDate: [
    { required: true, message: '请选择支出日期', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
});

// 获取活动详情
const getActivityDetail = async () => {
  try {
    const res = await ActivityAPI.getActivityForm(activityId.value);
    if (res.code === '200') {
      activityInfo.value = res.data;
    } else {
      ElMessage.error(res.msg || '获取活动详情失败');
    }
  } catch (error) {
    console.error('获取活动详情失败', error);
    ElMessage.error('获取活动详情失败');
  }
};

// 获取参与记录列表
const getParticipantList = async () => {
  participantLoading.value = true;
  try {
    const res = await ActivityAPI.getActivityParticipantPage({
      pageNum: 1,
      pageSize: 100,
      activityId: activityId.value
    });
    if (res.code === '200') {
      participantList.value = res.data.list;
    }
  } catch (error) {
    console.error('获取参与记录失败', error);
  } finally {
    participantLoading.value = false;
  }
};

// 获取评价列表
const getRatingList = async () => {
  ratingLoading.value = true;
  try {
    const res = await ActivityAPI.getActivityRatingPage({
      pageNum: 1,
      pageSize: 100,
      activityId: activityId.value
    });
    if (res.code === '200') {
      ratingList.value = res.data.list;
    }
  } catch (error) {
    console.error('获取评价列表失败', error);
  } finally {
    ratingLoading.value = false;
  }
};

// 获取预算列表
const getBudgetList = async () => {
  budgetLoading.value = true;
  try {
    const res = await ActivityAPI.getActivityBudgetPage({
      pageNum: 1,
      pageSize: 100,
      activityId: activityId.value
    });
    if (res.code === '200') {
      budgetList.value = res.data.list;
    }
  } catch (error) {
    console.error('获取预算列表失败', error);
  } finally {
    budgetLoading.value = false;
  }
};

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'PLANNED': return 'info';
    case 'ONGOING': return 'success';
    case 'COMPLETED': return 'primary';
    case 'CANCELLED': return 'danger';
    default: return 'info';
  }
};

// 获取状态标签
const getStatusLabel = (status) => {
  const option = activityStatusOptions.value.find(item => item.value === status);
  return option ? option.label : status;
};

// 编辑按钮
const handleEdit = () => {
  router.push({ path: `/activity/edit/${activityId.value}` });
};

// 返回按钮
const goBack = () => {
  router.push({ path: '/activity/list' });
};

// 添加参与记录
const handleAddParticipant = () => {
  participantForm.activityId = activityId.value;
  participantDialogVisible.value = true;
};

// 提交参与记录
const submitParticipant = () => {
  participantFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      const res = await ActivityAPI.addActivityParticipant(participantForm);
      if (res.code === '200') {
        ElMessage.success('添加参与记录成功');
        participantDialogVisible.value = false;
        getParticipantList();
      } else {
        ElMessage.error(res.msg || '添加参与记录失败');
      }
    } catch (error) {
      console.error('添加参与记录失败', error);
      ElMessage.error('添加参与记录失败，请稍后重试');
    }
  });
};

// 添加评价
const handleAddRating = () => {
  ratingForm.activityId = activityId.value;
  ratingDialogVisible.value = true;
};

// 提交评价
const submitRating = () => {
  ratingFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      const res = await ActivityAPI.addActivityRating(ratingForm);
      if (res.code === '200') {
        ElMessage.success('添加评价成功');
        ratingDialogVisible.value = false;
        getRatingList();
      } else {
        ElMessage.error(res.msg || '添加评价失败');
      }
    } catch (error) {
      console.error('添加评价失败', error);
      ElMessage.error('添加评价失败，请稍后重试');
    }
  });
};

// 添加预算
const handleAddBudget = () => {
  budgetForm.activityId = activityId.value;
  budgetDialogVisible.value = true;
};

// 提交预算
const submitBudget = () => {
  budgetFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      const res = await ActivityAPI.addActivityBudget(budgetForm);
      if (res.code === '200') {
        ElMessage.success('添加预算成功');
        budgetDialogVisible.value = false;
        getBudgetList();
      } else {
        ElMessage.error(res.msg || '添加预算失败');
      }
    } catch (error) {
      console.error('添加预算失败', error);
      ElMessage.error('添加预算失败，请稍后重试');
    }
  });
};

onMounted(() => {
  getActivityDetail();
  getParticipantList();
  getRatingList();
  getBudgetList();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.mt10 {
  margin-top: 10px;
}
.mt20 {
  margin-top: 20px;
}
.text-right {
  text-align: right;
}
</style> 